<template>
    <div class="prev-btn">
        <n-icon
            :component="ChevronBackCircleOutline"
            size="24"
            @click="prevClick()"
        >
        </n-icon>
    </div>
    <div class="next-btn">
        <n-icon
            :component="ChevronForwardCircleOutline"
            size="24"
            @click="nextClick()"
        >
        </n-icon>
    </div>
</template>
<script lang="ts" setup>
import {
    ChevronBackCircleOutline,
    ChevronForwardCircleOutline,
} from "@vicons/ionicons5";
import { computed, ref, watch } from "vue";
interface ResultData {
    data: Array<any>;
    totalPage: number;
}
interface ApiConfigData {
    page: number;
    apiFun: () => Promise<any>;
    resultHandle: (res: any) => ResultData;
}
const props = defineProps({
    list: {
        type: Array,
        default: () => [],
    },
    apiConfig: {
        type: Object as () => ApiConfigData,
        default: () => ({
            page: 1,
        }),
    },
    keyId: {
        type: String,
        default: "id",
    },
});

const curApiConfig = computed(() => {
    return {
        page: 1,
        resultHandle: (res) => {
            return {
                data: res.items,
                totalPage: Math.ceil(
                    res.page.total / (res.page.page_size || 20),
                ),
            };
        },
        ...props.apiConfig,
    };
});

const curPage = computed({
    get() {
        return curApiConfig.value.page;
    },
    set(value) {
        props.apiConfig.page = value;
        emits("update:apiConfig", props.apiConfig);
    },
});
const curLists = ref([]);
const emits = defineEmits(["switch", "update:apiConfig"]);
const current = ref(0);
const isFirst = computed(() => curApiConfig.value.page === 1);
let totalPage = 1;
const isLast = computed(() => curApiConfig.value.page === totalPage);
const allList = [];
const getApiData = () => {
    return new Promise<any[]>((resolve, reject) => {
        const apiConfig = curApiConfig.value;
        apiConfig.apiFun().then((res) => {
            let result = res;
            if (typeof apiConfig.resultHandle === "function") {
                result = apiConfig.resultHandle(res);
            }
            totalPage = result.totalPage;
            resolve(Array.isArray(result.data) ? result.data : []);
        });
    });
};
let loading = false;
// 由于curApiConfig.value.page 是真是响应的数据 ，需要个临时变量存当前页码
let curTpmPage = 1;
// 上一个
const prevClick = async () => {
    if (current.value === 0 && allList[curTpmPage - 1]) {
        curLists.value = allList[curTpmPage - 1];
        current.value = allList[curTpmPage - 1].length - 1;
        curTpmPage--;
        emits("switch", curLists.value[current.value]);
        return;
    }

    if (
        curLists.value.length &&
        current.value === 0 &&
        (!curApiConfig.value.apiFun ||
            (curApiConfig.value.apiFun && isFirst.value))
    ) {
        return;
    }
    if (current.value !== 0 && curLists.value.length) {
        current.value--;
        emits("switch", curLists.value[current.value]);
    }
    if (loading) return;
    // 当数据第3个的时候  获取上一页数据
    if (current.value === 3 && !isFirst.value && curApiConfig.value.apiFun) {
        curPage.value--;
        loading = true;
        let data = await getApiData();
        loading = false;
        if (data) {
            allList[curApiConfig.value.page] = data;
        }
    }
};
// 下一个
const nextClick = async () => {
    if (
        current.value === curLists.value.length - 1 &&
        allList[curTpmPage + 1]
    ) {
        curLists.value = allList[curTpmPage + 1];
        current.value = 0;
        curTpmPage++;
        emits("switch", curLists.value[current.value]);
        return;
    }
    if (
        curLists.value.length &&
        current.value === curLists.value.length - 1 &&
        (!curApiConfig.value.apiFun ||
            (curApiConfig.value.apiFun && isLast.value))
    ) {
        return;
    }
    if (current.value !== curLists.value.length - 1 && curLists.value.length) {
        current.value++;
        emits("switch", curLists.value[current.value]);
    }
    if (loading) return;
    //当数据倒数3个的时候  获取下一页数据 
    if (
    (current.value === curLists.value.length -4 || (current.value> curLists.value.length -4&&checkArrayNotNull(allList)<2)) &&
        !isLast.value &&
        curApiConfig.value.apiFun &&
        curApiConfig.value.page < totalPage
    ) {
        curPage.value++;
        loading = true;
        let data = await getApiData();
        loading = false;
        if (data) {
            allList[curApiConfig.value.page] = data;
        }
    }
};
const checkArrayNotNull = (arr) => {
    return arr.filter((item) => item).length;
};

const initData = async (id) => {
    if (curLists.value.length) {
        current.value = curLists.value.findIndex(
            (item) => item[props.keyId] === id,
        );
    }
    if (current.value === -1) {
        current.value = 0;
    }
    curTpmPage =curApiConfig.value.page
    const apiConfig = curApiConfig.value;
    if (apiConfig.apiFun) {
        let data = await getApiData();
        if (data) {
            allList[curApiConfig.value.page] = data;
            curLists.value = data;
            current.value = data.findIndex((item) => item[props.keyId] === id);
        }
    }
};
watch(
    props.list,
    (newVal) => {
        allList[curApiConfig.value.page] = newVal;
        curLists.value = newVal;
    },
    {
        deep: true,
        immediate: true,
    },
);

defineExpose({
    initData,
});
</script>
<style>
.next-btn,
.prev-btn {
    cursor: pointer;
    position: absolute;
    top: 50%;
}
.next-btn {
    right: 0;
}
.prev-btn {
    left: 0;
}
</style>